package tech.xiaozai.exam.security;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.SmartLifecycle;
import org.springframework.security.core.GrantedAuthority;
import tech.xiaozai.exam.custom.mapper.CustomPermissionMapper;
import tech.xiaozai.exam.custom.po.RolePermissionItem;

import java.util.*;

/**
 * @author xiaozai
 * @version 1.0
 * @date 2020-09-23 19:28
 *
 *  在IOC容器启动后，所有bean完成之后去调这个接口
 */
@Slf4j
public class LoadPermissionAfterIOCRunning implements SmartLifecycle {


    @Autowired
    private CustomPermissionMapper customPermissionMapper;


    private Map<String,Set<GrantedAuthority>> cache = new HashMap<>();


    public final Map<String, Set<String>> table = new HashMap<>(7);


    /**
     *  刷新权限表
     */
    public void refresh(){
        cache.clear();
        table.clear();
        /**
         *   rid  pid   keyword         name
         *    1    1    url:user:add    添加用户
         *    1    2    url:role:delete 删除角色
         *    1    3    ....
         *    2    2    ....
         *    2    3
         *    2    4
         *    ...  ..
         *
         *
         *    构建:    1-> ["url:user:list" ,"url:user:add" ]
         *
         *            ..  ...
         */

        List<RolePermissionItem> items = customPermissionMapper.getAllRolePermissionItem();

        items.forEach(item->{
            System.out.println("item="+item);
            Set<String> set = table.get(item.getRoleId().toString());

            if(set==null) {
                set = new HashSet<>();
                table.put(item.getRoleId().toString(), set);
            }
            set.add(item.getKeyword());
        });

    }


    /**
     *
     * @param roleIds
     * @return
     */
    public Collection<GrantedAuthority> keywords(Collection<String> roleIds){
        Integer key=0;
        //将原来的roleIds转整型集合
        List<Integer> rids = roleIds.stream().mapToInt(id -> Integer.parseInt(id))
                .collect(ArrayList::new,List::add,List::addAll);
        for(Integer rid: rids){
            key += rid;
        }

        //先从缓存中去,如果取出来不为空，直接返回
        Set<GrantedAuthority> set = cache.get(key.toString());
        if(set!=null){
            return  set;
        }

        //缓存中没有
        set = new HashSet<>();
        for(String rid: roleIds){
            Set<String> keywords = table.get(rid);
            if(keywords==null){
                continue;
            }
            for(String kw: keywords){
                set.add(new MyGrantedAuthority().setAuthority(kw));
            }
        }
        //保存到缓存中
        cache.put(key.toString(),set);
        return set;


        /**
         *   1-> [ "url:user:list","url:user:add","url:user:delete"]
         *   2-> [ "url:role:list","url:role:add" ,"url:user:list"]
         *
         *   应该返回:   [ "url:user:list","url:user:add","url:user:delete",  "url:role:list","url:role:add"   ]
         *
         */
    }

    @Override
    public void start() {
        if(log.isDebugEnabled()){
            log.debug("所有bean准备好了，我要开始加载权限表");
        }
        refresh();
       if(log.isDebugEnabled()){
           log.debug("权限表加载完毕,table="+table);
       }
    }

    @Override
    public void stop() {

    }

    @Override
    public boolean isRunning() {
        return false;
    }
}
